<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>简单MQTT客户端</title>
    <script src="https://unpkg.com/mqtt/dist/mqtt.min.js"></script>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 600px;
            margin: 50px auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .container {
            background: white;
            padding: 30px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .status {
            padding: 10px;
            border-radius: 5px;
            margin-bottom: 20px;
            text-align: center;
            font-weight: bold;
        }
        .connected {
            background-color: #d4edda;
            color: #155724;
        }
        .disconnected {
            background-color: #f8d7da;
            color: #721c24;
        }
        button {
            padding: 10px 20px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 16px;
            margin: 5px;
        }
        .btn-connect {
            background-color: #007bff;
            color: white;
        }
        .btn-disconnect {
            background-color: #dc3545;
            color: white;
        }
        .messages {
            border: 1px solid #ddd;
            border-radius: 5px;
            padding: 15px;
            height: 300px;
            overflow-y: auto;
            background-color: #f8f9fa;
            font-family: monospace;
            font-size: 14px;
        }
        .message {
            margin-bottom: 10px;
            padding: 8px;
            border-radius: 5px;
            background-color: #e3f2fd;
            border-left: 4px solid #2196f3;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>🔌 简单MQTT客户端</h1>
        <p>连接到 broker.emqx.io 接收"哈哈哈哈"主题的消息</p>
        
        <div style="background-color: #e3f2fd; padding: 15px; border-radius: 5px; margin-bottom: 20px; border-left: 4px solid #2196f3;">
            <h4>📋 如何在MQTTX中接收消息：</h4>
            <ol style="margin: 10px 0; padding-left: 20px;">
                <li><strong>连接MQTTX</strong>：连接到 broker.emqx.io:1883</li>
                <li><strong>添加订阅</strong>：点击"+"号，订阅主题 "哈哈哈哈"</li>
                <li><strong>接收消息</strong>：HTML发送的消息会出现在MQTTX的"已接收"标签页</li>
            </ol>
        </div>
        
        <div id="status" class="status disconnected">
            未连接
        </div>
        
        <div style="text-align: center; margin-bottom: 20px;">
            <button class="btn-connect" onclick="connect()">连接</button>
            <button class="btn-disconnect" onclick="disconnect()">断开</button>
        </div>
        
        <div style="background-color: #f8f9fa; padding: 20px; border-radius: 5px; margin-bottom: 20px;">
            <h3>📤 发送消息</h3>
            <div style="margin-bottom: 15px;">
                <label style="display: block; margin-bottom: 5px; font-weight: bold;">主题:</label>
                <input type="text" id="sendTopic" value="哈哈哈哈" style="width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px; box-sizing: border-box;">
            </div>
            <div style="margin-bottom: 15px;">
                <label style="display: block; margin-bottom: 5px; font-weight: bold;">消息内容:</label>
                <textarea id="sendMessage" rows="3" placeholder="输入要发送的消息" style="width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px; box-sizing: border-box;"></textarea>
            </div>
            <button class="btn-connect" onclick="sendMessage()" style="width: 100%;">发送消息</button>
        </div>
        
        <h3>收到的消息：</h3>
        <div id="messages" class="messages"></div>
    </div>

    <script>
        let client = null;
        let isConnected = false;

        // 连接MQTT服务器
        function connect() {
            if (isConnected) {
                alert('已经连接了！');
                return;
            }

            try {
                // 连接到EMQX公共服务器
                const connectUrl = 'ws://broker.emqx.io:8083/mqtt';
                const options = {
                    clientId: 'html_client_' + Math.random().toString(16).substring(2, 8),
                    clean: true,
                    connectTimeout: 30 * 1000,
                    reconnectPeriod: 4000,
                };

                console.log('正在连接到:', connectUrl);
                
                client = mqtt.connect(connectUrl, options);

                client.on('connect', () => {
                    isConnected = true;
                    updateStatus(true);
                    addMessage('✅ 连接成功！');
                    
                    // 自动订阅"哈哈哈哈"主题
                    client.subscribe('哈哈哈哈', (error) => {
                        if (error) {
                            addMessage('❌ 订阅失败: ' + error.message);
                        } else {
                            addMessage('📡 已订阅主题: 哈哈哈哈');
                        }
                    });
                });

                client.on('error', (error) => {
                    addMessage('❌ 连接错误: ' + error.message);
                    updateStatus(false);
                });

                client.on('close', () => {
                    addMessage('🔌 连接已关闭');
                    updateStatus(false);
                });

                client.on('message', (topic, message) => {
                    const messageStr = message.toString();
                    addMessage(`📨 收到消息 [${topic}]: ${messageStr}`);
                });

            } catch (error) {
                addMessage('❌ 连接失败: ' + error.message);
            }
        }

        // 发送消息
        function sendMessage() {
            if (!client || !isConnected) {
                addMessage('❌ 请先连接到MQTT服务器');
                return;
            }

            const topic = document.getElementById('sendTopic').value;
            const message = document.getElementById('sendMessage').value;

            if (!topic || !message) {
                addMessage('❌ 主题和消息内容不能为空');
                return;
            }

            try {
                client.publish(topic, message, { qos: 0 }, (error) => {
                    if (error) {
                        addMessage(`❌ 发送失败: ${error.message}`);
                    } else {
                        addMessage(`📤 发送消息 [${topic}]: ${message}`);
                        // 清空消息输入框
                        document.getElementById('sendMessage').value = '';
                    }
                });
            } catch (error) {
                addMessage(`❌ 发送失败: ${error.message}`);
            }
        }

        // 断开连接
        function disconnect() {
            if (client && isConnected) {
                client.end();
                client = null;
                isConnected = false;
                updateStatus(false);
                addMessage('🔌 已断开连接');
            } else {
                addMessage('当前未连接');
            }
        }

        // 更新连接状态显示
        function updateStatus(connected) {
            const statusElement = document.getElementById('status');
            isConnected = connected;
            
            if (connected) {
                statusElement.className = 'status connected';
                statusElement.textContent = '✅ 已连接';
            } else {
                statusElement.className = 'status disconnected';
                statusElement.textContent = '❌ 未连接';
            }
        }

        // 添加消息到显示区域
        function addMessage(message) {
            const messagesDiv = document.getElementById('messages');
            const messageElement = document.createElement('div');
            messageElement.className = 'message';
            
            const timestamp = new Date().toLocaleTimeString();
            messageElement.innerHTML = `<strong>[${timestamp}]</strong> ${message}`;
            
            messagesDiv.appendChild(messageElement);
            messagesDiv.scrollTop = messagesDiv.scrollHeight;
        }

        // 页面加载时显示初始信息
        window.onload = function() {
            addMessage('🚀 MQTT客户端已准备就绪');
            addMessage('点击"连接"按钮开始接收消息');
        };
    </script>
</body>
</html>
